package nacos

import (
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/zero-contrib/zrpc/registry/nacos"
	_ "github.com/zeromicro/zero-contrib/zrpc/registry/nacos"
	"go-zero-demo/common/tools"
	"go-zero-demo/user-api/internal/config"
	"os"
	"strconv"
	"strings"
)

const defaultRpcCacheDir = "cache//naming"
const nacosCacheDir = "NACOS_CACHE_DIR"

func initNaocsConfig(conf *config.NacosConfig) ([]constant.ServerConfig, constant.ClientConfig) {
	//create ServerConfig
	sc := []constant.ServerConfig{
		{
			IpAddr:      conf.Addr,
			ContextPath: conf.ContextPath,
			Port:        conf.Port,
			Scheme:      conf.Scheme,
		},
	}
	//create ClientConfig
	cc := *constant.NewClientConfig(
		constant.WithNamespaceId(conf.NamespaceId),
		constant.WithTimeoutMs(conf.TimeoutMs),
		constant.WithLogDir(conf.LogDir),
		constant.WithCacheDir(conf.CacheDir),
		constant.WithLogLevel(conf.LogLevel),
		constant.WithUsername(conf.Username),
		constant.WithPassword(conf.Password),
		constant.WithUpdateThreadNum(conf.UpdateThreadNum),
		constant.WithNotLoadCacheAtStart(conf.NotLoadCacheAtStart),
		constant.WithUpdateCacheWhenEmpty(conf.UpdateCacheWhenEmpty),
	)
	return sc, cc
}

func RegisterNacos(c config.Config) {
	fixNacosRpcCacheBug()
	// 初始化配置
	sc, cc := initNaocsConfig(c.Nacos)
	options := nacos.NewNacosConfig(c.Name, c.Host+":"+strconv.Itoa(c.Port), sc, &cc)
	options.Group = c.Nacos.Group
	options.Weight = 1
	options.Cluster = "cluster-zwx"
	options.Metadata = map[string]string{"idc": "shanghai"}
	options.ServiceName = c.Nacos.AppName
	err := nacos.RegisterService(options)
	if err != nil {
		logx.Error(err.Error())
		return
	}
}

// fixNacosRpcCacheBug 修复nacos rcp cache bug
func fixNacosRpcCacheBug() {
	// 这里存在一个bug 如果清除缓存导致重启后会rpc调用失败
	getEnv := os.Getenv(nacosCacheDir)
	// 配置cache路径则取配置的路径
	if len(strings.TrimSpace(getEnv)) > 0 {
		exists, existsErr := tools.PathExists(getEnv)
		if existsErr != nil {
			logx.Errorf("判断文件是否存在错误%s", existsErr.Error())
		}
		if exists {
			err := os.RemoveAll(getEnv)
			if err != nil {
				logx.Errorf("删除文件是否存在错误%s", existsErr.Error())
			}
		}
	} else {
		// 否则走默认配置
		exists, existsErr := tools.PathExists(defaultRpcCacheDir)
		if existsErr != nil {
			logx.Errorf("判断文件是否存在错误%s", existsErr.Error())
		}
		if exists {
			err := os.RemoveAll(defaultRpcCacheDir)
			if err != nil {
				logx.Errorf("删除文件是否存在错误%s", err.Error())
			}
		}
	}
}
